const fs = require("fs-extra");
const path = require("path");
const chalk = require("chalk");
const symbols = require("log-symbols");
const inquirer = require("inquirer");
const ora = require("ora");
const download = require("download-git-repo");

// const packageConfig = require('../package.json')
const spinner = ora("下载中...");

// 新建项目
async function create(projectName, options) {
  // 获取当前路径
  const cwd = process.cwd();
  // 看看是不是有人敲了路径
  // const inCurrent = projectName === '.'
  // const name = inCurrent ? path.relative('../', cwd) : projectName
  const targetDir = path.resolve(cwd, projectName || ".");
  // 判断当前路径下是否有这个文件夹
  if (!fs.existsSync(targetDir)) {
    // 没有
    // 1.创建交互
    const promptList = [
      // 具体交互内容
      {
        type: "input",
        name: "name",
        message: "项目名称:",
        default: projectName,
      },
      {
        type: "input",
        name: "author",
        message: "作者/团队:",
        default: "front-end team of BFSI1_BUCMT_CL_CLP",
      },
      {
        type: "input",
        name: "description",
        message: "描述:",
        default: "",
      },
    ];
    inquirer.prompt(promptList).then((answers) => {
      // 2.拉取模板
      const { name, description, author } = answers;
      // 模板
      let url = "direct:https://gitee.com/xifeiliu/template_a.git#master";
      console.log("正在拉取项目模板...");
      spinner.start();
      downTemplate(url, projectName, () => {
        writePackageJson(targetDir, answers);
        // // 修改本地数据
        // successConsole(projectName)
      });
    });
  } else {
    // 有
    throw Error("当前路径已存在同名目录，请确定后再试");
  }
}
// 下载成功后重写package
function writePackageJson(targetDir, answers) {
  const { description, author, name } = answers;
  let packpath = targetDir + "/package.json";
  // 读取package内容
  let tmpJson = fs.readFileSync(packpath);
  let packageJson = JSON.parse(tmpJson);
  let result = {
    ...packageJson,
    name,
    description,
    author,
  };

  fs.writeFile(packpath, JSON.stringify(result, null, "\t"), function (err) {
    if (err) throw err;
    successConsole(name);
  });
}

// 成功后的输出
function successConsole(projectName) {
  console.log(chalk.green("success"));
  console.log(chalk.green(`${projectName}创建成功, 执行下面命令启动项目`));
  console.log(chalk.green(` cd ${projectName}`));
  console.log(chalk.green(" yarn"));
  console.log(chalk.green(" yarn serve"));
}

// 下载模板
function downTemplate(url, projectName, callback) {
  download(url, projectName, { clone: true }, (err) => {
    // 判断是否下载失败
    if (err) {
      // 下载失败
      spinner.fail();
      throw err;
    } else {
      // 下载成功
      spinner.succeed();
      callback();
    }
  });
}

module.exports = (...args) => {
  return create(...args).catch((err) => {
    console.log(symbols.error, chalk.red(err));
    process.exit(1);
    // console.error(chalk.red.dim('出错了，憨批Error: ' + err))
    // stopSpinner(false) // do not persist
    // error(err)
    // if (!process.env.VUE_CLI_TEST) {
    // process.exit(1)
    // }
  });
};
